package com.fezs.message.config;

import cn.hutool.core.net.NetUtil;
import com.fezs.message.config.properties.MessageProperties;
import com.fezs.message.entity.MsgEntity;
import com.fezs.message.template.MessageTemplate;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author zhukai
 * @since 2022/8/18
 */
@Slf4j
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties({MessageProperties.class})
@ConditionalOnProperty(prefix = "message.notice", name = "enabled", havingValue = "true")
public class WxMsgConfig {

    @Bean
    @ConditionalOnMissingBean
    public MessageTemplate messageTemplate(MessageProperties prop) {
        MessageTemplate messageTemplate = new MessageTemplate();
        messageTemplate.setKey(prop.getKey());
        messageTemplate.setProxyHost(prop.getProxyHost());
        messageTemplate.setProxyPort(prop.getProxyPort());
        return messageTemplate;
    }

    @Bean
    public AppStartedRunner appStartedRunner(MessageTemplate messageTemplate) {
        return new AppStartedRunner(messageTemplate);
    }

    @RequiredArgsConstructor
    public static class AppStartedRunner implements ApplicationRunner, DisposableBean {

        @Value("${spring.application.name}")
        private String appName;

        @Value("${spring.profiles.active}")
        private String profile;

        private final MessageTemplate messageTemplate;

        @Override
        public void run(ApplicationArguments args) {
            String content = String.format("服务[%s]环境[%s]启动成功! IP:%s", appName, profile, NetUtil.getLocalhostStr());
            messageTemplate.send(MsgEntity.buildTextMsg(content));
        }

        @Override
        public void destroy() {
            String content = String.format("服务[%s]环境[%s]即将关闭! IP:%s", appName, profile, NetUtil.getLocalhostStr());
            messageTemplate.send(MsgEntity.buildTextMsg(content));
        }
    }

}
